3 * This is the MySQL database abstraction layer.
10 * Database abstraction object for mySQL
11 * Inherit all methods and properties of Database::Database()
16 class DatabaseMysql
extends DatabaseBase
{
29 protected function doQuery( $sql ) {
30 if( $this->bufferResults() ) {
31 $ret = mysql_query( $sql, $this->mConn
);
33 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
39 * @param $server string
41 * @param $password string
42 * @param $dbName string
44 * @throws DBConnectionError
46 function open( $server, $user, $password, $dbName ) {
47 global $wgAllDBsAreLocalhost;
48 wfProfileIn( __METHOD__
);
50 # Load mysql.so if we don't have it
54 # Otherwise we get a suppressed fatal error, which is very hard to track down
55 if ( !function_exists( 'mysql_connect' ) ) {
56 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
59 # Debugging hack -- fake cluster
60 if ( $wgAllDBsAreLocalhost ) {
61 $realServer = 'localhost';
63 $realServer = $server;
66 $this->mServer
= $server;
68 $this->mPassword
= $password;
69 $this->mDBname
= $dbName;
71 wfProfileIn("dbconnect-$server");
73 # The kernel's default SYN retransmission period is far too slow for us,
74 # so we use a short timeout plus a manual retry. Retrying means that a small
75 # but finite rate of SYN packet loss won't cause user-visible errors.
77 if ( ini_get( 'mysql.connect_timeout' ) <= 3 ) {
82 $this->installErrorHandler();
83 for ( $i = 0; $i < $numAttempts && !$this->mConn
; $i++
) {
87 if ( $this->mFlags
& DBO_PERSISTENT
) {
88 $this->mConn
= mysql_pconnect( $realServer, $user, $password );
90 # Create a new connection...
91 $this->mConn
= mysql_connect( $realServer, $user, $password, true );
93 #if ( $this->mConn === false ) {
95 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
98 $phpError = $this->restoreErrorHandler();
99 # Always log connection errors
100 if ( !$this->mConn
) {
101 $error = $this->lastError();
105 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
106 wfDebug( "DB connection error\n" );
107 wfDebug( "Server: $server, User: $user, Password: " .
108 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
111 wfProfileOut("dbconnect-$server");
113 if ( $dbName != '' && $this->mConn
!== false ) {
114 wfSuppressWarnings();
115 $success = mysql_select_db( $dbName, $this->mConn
);
118 $error = "Error selecting database $dbName on server {$this->mServer} " .
119 "from client host " . wfHostname() . "\n";
120 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
125 $success = (bool)$this->mConn
;
129 // Tell the server we're communicating with it in UTF-8.
130 // This may engage various charset conversions.
133 $this->query( 'SET NAMES utf8', __METHOD__
);
135 $this->query( 'SET NAMES binary', __METHOD__
);
137 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
139 if ( is_string( $wgSQLMode ) ) {
140 $mode = $this->addQuotes( $wgSQLMode );
141 $this->query( "SET sql_mode = $mode", __METHOD__
);
144 // Turn off strict mode if it is on
146 $this->reportConnectionError( $phpError );
149 $this->mOpened
= $success;
150 wfProfileOut( __METHOD__
);
158 $this->mOpened
= false;
159 if ( $this->mConn
) {
160 if ( $this->trxLevel() ) {
161 $this->commit( __METHOD__
);
163 $ret = mysql_close( $this->mConn
);
164 $this->mConn
= false;
172 * @param $res ResultWrapper
173 * @throws DBUnexpectedError
175 function freeResult( $res ) {
176 if ( $res instanceof ResultWrapper
) {
179 wfSuppressWarnings();
180 $ok = mysql_free_result( $res );
183 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
188 * @param $res ResultWrapper
189 * @return object|stdClass
190 * @throws DBUnexpectedError
192 function fetchObject( $res ) {
193 if ( $res instanceof ResultWrapper
) {
196 wfSuppressWarnings();
197 $row = mysql_fetch_object( $res );
199 if( $this->lastErrno() ) {
200 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
206 * @param $res ResultWrapper
208 * @throws DBUnexpectedError
210 function fetchRow( $res ) {
211 if ( $res instanceof ResultWrapper
) {
214 wfSuppressWarnings();
215 $row = mysql_fetch_array( $res );
217 if ( $this->lastErrno() ) {
218 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
224 * @throws DBUnexpectedError
225 * @param $res ResultWrapper
228 function numRows( $res ) {
229 if ( $res instanceof ResultWrapper
) {
232 wfSuppressWarnings();
233 $n = mysql_num_rows( $res );
235 if( $this->lastErrno() ) {
236 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
242 * @param $res ResultWrapper
245 function numFields( $res ) {
246 if ( $res instanceof ResultWrapper
) {
249 return mysql_num_fields( $res );
253 * @param $res ResultWrapper
257 function fieldName( $res, $n ) {
258 if ( $res instanceof ResultWrapper
) {
261 return mysql_field_name( $res, $n );
267 function insertId() {
268 return mysql_insert_id( $this->mConn
);
272 * @param $res ResultWrapper
276 function dataSeek( $res, $row ) {
277 if ( $res instanceof ResultWrapper
) {
280 return mysql_data_seek( $res, $row );
286 function lastErrno() {
287 if ( $this->mConn
) {
288 return mysql_errno( $this->mConn
);
290 return mysql_errno();
297 function lastError() {
298 if ( $this->mConn
) {
299 # Even if it's non-zero, it can still be invalid
300 wfSuppressWarnings();
301 $error = mysql_error( $this->mConn
);
303 $error = mysql_error();
307 $error = mysql_error();
310 $error .= ' (' . $this->mServer
. ')';
318 function affectedRows() {
319 return mysql_affected_rows( $this->mConn
);
323 * @param $table string
324 * @param $uniqueIndexes
326 * @param $fname string
327 * @return ResultWrapper
329 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseMysql::replace' ) {
330 return $this->nativeReplace( $table, $rows, $fname );
334 * Estimate rows in dataset
335 * Returns estimated count, based on EXPLAIN output
336 * Takes same arguments as Database::select()
338 * @param $table string|array
339 * @param $vars string|array
340 * @param $conds string|array
341 * @param $fname string
342 * @param $options string|array
345 public function estimateRowCount( $table, $vars='*', $conds='', $fname = 'DatabaseMysql::estimateRowCount', $options = array() ) {
346 $options['EXPLAIN'] = true;
347 $res = $this->select( $table, $vars, $conds, $fname, $options );
348 if ( $res === false ) {
351 if ( !$this->numRows( $res ) ) {
356 foreach ( $res as $plan ) {
357 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
363 * @param $table string
364 * @param $field string
365 * @return bool|MySQLField
367 function fieldInfo( $table, $field ) {
368 $table = $this->tableName( $table );
369 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
373 $n = mysql_num_fields( $res->result
);
374 for( $i = 0; $i < $n; $i++
) {
375 $meta = mysql_fetch_field( $res->result
, $i );
376 if( $field == $meta->name
) {
377 return new MySQLField($meta);
384 * Get information about an index into an object
385 * Returns false if the index does not exist
387 * @param $table string
388 * @param $index string
389 * @param $fname string
390 * @return bool|array|null False or null on failure
392 function indexInfo( $table, $index, $fname = 'DatabaseMysql::indexInfo' ) {
393 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
394 # SHOW INDEX should work for 3.x and up:
395 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
396 $table = $this->tableName( $table );
397 $index = $this->indexName( $index );
398 $sql = 'SHOW INDEX FROM ' . $table;
399 $res = $this->query( $sql, $fname );
407 foreach ( $res as $row ) {
408 if ( $row->Key_name
== $index ) {
413 return empty( $result ) ?
false : $result;
420 function selectDB( $db ) {
421 $this->mDBname
= $db;
422 return mysql_select_db( $db, $this->mConn
);
430 function strencode( $s ) {
431 $sQuoted = mysql_real_escape_string( $s, $this->mConn
);
433 if($sQuoted === false) {
435 $sQuoted = mysql_real_escape_string( $s, $this->mConn
);
441 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
447 public function addIdentifierQuotes( $s ) {
448 return "`" . $this->strencode( $s ) . "`";
452 * @param $name string
455 public function isQuotedIdentifier( $name ) {
456 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
463 $ping = mysql_ping( $this->mConn
);
468 mysql_close( $this->mConn
);
469 $this->mOpened
= false;
470 $this->mConn
= false;
471 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
478 * This will do a SHOW SLAVE STATUS
483 if ( !is_null( $this->mFakeSlaveLag
) ) {
484 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
485 return $this->mFakeSlaveLag
;
488 return $this->getLagFromSlaveStatus();
494 function getLagFromSlaveStatus() {
495 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
499 $row = $res->fetchObject();
503 if ( strval( $row->Seconds_Behind_Master
) === '' ) {
506 return intval( $row->Seconds_Behind_Master
);
511 * @deprecated in 1.19, use getLagFromSlaveStatus
515 function getLagFromProcesslist() {
516 wfDeprecated( __METHOD__
, '1.19' );
517 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__
);
521 # Find slave SQL thread
522 foreach( $res as $row ) {
523 /* This should work for most situations - when default db
524 * for thread is not specified, it had no events executed,
525 * and therefore it doesn't know yet how lagged it is.
527 * Relay log I/O thread does not select databases.
529 if ( $row->User
== 'system user' &&
530 $row->State
!= 'Waiting for master to send event' &&
531 $row->State
!= 'Connecting to master' &&
532 $row->State
!= 'Queueing master event to the relay log' &&
533 $row->State
!= 'Waiting for master update' &&
534 $row->State
!= 'Requesting binlog dump' &&
535 $row->State
!= 'Waiting to reconnect after a failed master event read' &&
536 $row->State
!= 'Reconnecting after a failed master event read' &&
537 $row->State
!= 'Registering slave on master'
539 # This is it, return the time (except -ve)
540 if ( $row->Time
> 0x7fffffff ) {
551 * Wait for the slave to catch up to a given master position.
553 * @param $pos DBMasterPos object
554 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
555 * @return bool|string
557 function masterPosWait( DBMasterPos
$pos, $timeout ) {
558 $fname = 'DatabaseBase::masterPosWait';
559 wfProfileIn( $fname );
561 # Commit any open transactions
562 if ( $this->mTrxLevel
) {
563 $this->commit( __METHOD__
);
566 if ( !is_null( $this->mFakeSlaveLag
) ) {
567 $status = parent
::masterPosWait( $pos, $timeout );
568 wfProfileOut( $fname );
572 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
573 $encFile = $this->addQuotes( $pos->file
);
574 $encPos = intval( $pos->pos
);
575 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
576 $res = $this->doQuery( $sql );
578 if ( $res && $row = $this->fetchRow( $res ) ) {
579 wfProfileOut( $fname );
582 wfProfileOut( $fname );
588 * Get the position of the master from SHOW SLAVE STATUS
590 * @return MySQLMasterPos|bool
592 function getSlavePos() {
593 if ( !is_null( $this->mFakeSlaveLag
) ) {
594 return parent
::getSlavePos();
597 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
598 $row = $this->fetchObject( $res );
601 $pos = isset( $row->Exec_master_log_pos
) ?
$row->Exec_master_log_pos
: $row->Exec_Master_Log_Pos
;
602 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
609 * Get the position of the master from SHOW MASTER STATUS
611 * @return MySQLMasterPos|bool
613 function getMasterPos() {
614 if ( $this->mFakeMaster
) {
615 return parent
::getMasterPos();
618 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
619 $row = $this->fetchObject( $res );
622 return new MySQLMasterPos( $row->File
, $row->Position
);
631 function getServerVersion() {
632 return mysql_get_server_info( $this->mConn
);
639 function useIndexClause( $index ) {
640 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
646 function lowPriorityOption() {
647 return 'LOW_PRIORITY';
653 public static function getSoftwareLink() {
654 return '[http://www.mysql.com/ MySQL]';
660 function standardSelectDistinct() {
665 * @param $options array
667 public function setSessionOptions( array $options ) {
668 if ( isset( $options['connTimeout'] ) ) {
669 $timeout = (int)$options['connTimeout'];
670 $this->query( "SET net_read_timeout=$timeout" );
671 $this->query( "SET net_write_timeout=$timeout" );
675 public function streamStatementEnd( &$sql, &$newLine ) {
676 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
677 preg_match( '/^DELIMITER\s+(\S+)/' , $newLine, $m );
678 $this->delimiter
= $m[1];
681 return parent
::streamStatementEnd( $sql, $newLine );
685 * @param $lockName string
686 * @param $method string
687 * @param $timeout int
690 public function lock( $lockName, $method, $timeout = 5 ) {
691 $lockName = $this->addQuotes( $lockName );
692 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
693 $row = $this->fetchObject( $result );
695 if( $row->lockstatus
== 1 ) {
698 wfDebug( __METHOD__
." failed to acquire lock\n" );
704 * FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
705 * @param $lockName string
706 * @param $method string
709 public function unlock( $lockName, $method ) {
710 $lockName = $this->addQuotes( $lockName );
711 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
712 $row = $this->fetchObject( $result );
713 return $row->lockstatus
;
718 * @param $write array
719 * @param $method string
720 * @param $lowPriority bool
722 public function lockTables( $read, $write, $method, $lowPriority = true ) {
725 foreach( $write as $table ) {
726 $tbl = $this->tableName( $table ) .
727 ( $lowPriority ?
' LOW_PRIORITY' : '' ) .
731 foreach( $read as $table ) {
732 $items[] = $this->tableName( $table ) . ' READ';
734 $sql = "LOCK TABLES " . implode( ',', $items );
735 $this->query( $sql, $method );
739 * @param $method string
741 public function unlockTables( $method ) {
742 $this->query( "UNLOCK TABLES", $method );
746 * Get search engine class. All subclasses of this
747 * need to implement this if they wish to use searching.
751 public function getSearchEngine() {
752 return 'SearchMySQL';
759 public function setBigSelects( $value = true ) {
760 if ( $value === 'default' ) {
761 if ( $this->mDefaultBigSelects
=== null ) {
762 # Function hasn't been called before so it must already be set to the default
765 $value = $this->mDefaultBigSelects
;
767 } elseif ( $this->mDefaultBigSelects
=== null ) {
768 $this->mDefaultBigSelects
= (bool)$this->selectField( false, '@@sql_big_selects' );
770 $encValue = $value ?
'1' : '0';
771 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
775 * DELETE where the condition is a join. MySql uses multi-table deletes.
776 * @param $delTable string
777 * @param $joinTable string
778 * @param $delVar string
779 * @param $joinVar string
780 * @param $conds array|string
782 * @return bool|ResultWrapper
784 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseBase::deleteJoin' ) {
786 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
789 $delTable = $this->tableName( $delTable );
790 $joinTable = $this->tableName( $joinTable );
791 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
793 if ( $conds != '*' ) {
794 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
797 return $this->query( $sql, $fname );
801 * Determines how long the server has been up
805 function getServerUptime() {
806 $vars = $this->getMysqlStatus( 'Uptime' );
807 return (int)$vars['Uptime'];
811 * Determines if the last failure was due to a deadlock
815 function wasDeadlock() {
816 return $this->lastErrno() == 1213;
820 * Determines if the last failure was due to a lock timeout
824 function wasLockTimeout() {
825 return $this->lastErrno() == 1205;
829 * Determines if the last query error was something that should be dealt
830 * with by pinging the connection and reissuing the query
834 function wasErrorReissuable() {
835 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
839 * Determines if the last failure was due to the database being read-only.
843 function wasReadOnlyError() {
844 return $this->lastErrno() == 1223 ||
845 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
851 * @param $temporary bool
852 * @param $fname string
854 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseMysql::duplicateTableStructure' ) {
855 $tmp = $temporary ?
'TEMPORARY ' : '';
856 $newName = $this->addIdentifierQuotes( $newName );
857 $oldName = $this->addIdentifierQuotes( $oldName );
858 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
859 $this->query( $query, $fname );
863 * List all tables on the database
865 * @param $prefix string Only show tables with this prefix, e.g. mw_
866 * @param $fname String: calling function name
869 function listTables( $prefix = null, $fname = 'DatabaseMysql::listTables' ) {
870 $result = $this->query( "SHOW TABLES", $fname);
874 foreach( $result as $table ) {
875 $vars = get_object_vars($table);
876 $table = array_pop( $vars );
878 if( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
879 $endArray[] = $table;
888 * @param $fName string
889 * @return bool|ResultWrapper
891 public function dropTable( $tableName, $fName = 'DatabaseMysql::dropTable' ) {
892 if( !$this->tableExists( $tableName, $fName ) ) {
895 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
901 protected function getDefaultSchemaVars() {
902 $vars = parent
::getDefaultSchemaVars();
903 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
904 $vars['wgDBTableOptions'] = str_replace( 'CHARSET=mysql4', 'CHARSET=binary', $vars['wgDBTableOptions'] );
909 * Get status information from SHOW STATUS in an associative array
911 * @param $which string
914 function getMysqlStatus( $which = "%" ) {
915 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
918 foreach ( $res as $row ) {
919 $status[$row->Variable_name
] = $row->Value
;
928 * Legacy support: Database == DatabaseMysql
930 * @deprecated in 1.16
932 class Database
extends DatabaseMysql
{}
938 class MySQLField
implements Field
{
939 private $name, $tablename, $default, $max_length, $nullable,
940 $is_pk, $is_unique, $is_multiple, $is_key, $type;
942 function __construct ( $info ) {
943 $this->name
= $info->name
;
944 $this->tablename
= $info->table
;
945 $this->default = $info->def
;
946 $this->max_length
= $info->max_length
;
947 $this->nullable
= !$info->not_null
;
948 $this->is_pk
= $info->primary_key
;
949 $this->is_unique
= $info->unique_key
;
950 $this->is_multiple
= $info->multiple_key
;
951 $this->is_key
= ( $this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
952 $this->type
= $info->type
;
965 function tableName() {
966 return $this->tableName
;
979 function isNullable() {
980 return $this->nullable
;
983 function defaultValue() {
984 return $this->default;
991 return $this->is_key
;
997 function isMultipleKey() {
998 return $this->is_multiple
;
1002 class MySQLMasterPos
implements DBMasterPos
{
1005 function __construct( $file, $pos ) {
1006 $this->file
= $file;
1010 function __toString() {
1011 return "{$this->file}/{$this->pos}";